//index.js
//获取应用实例
const app = getApp();
const request = require('../../../utils/request.js');
Component({
  options: {
    addGlobalClass: true,
  },
  data: {
    videoUrl: '',
    videoTitle: '',
    isShow: false,
    isDownload: false,
    isButton: true,
    list: []
  },

  //组件的生命周期
  lifetimes: {
    created: function () {
      if (!wx.getStorageSync('openId')) {
      //初始化次数及信息
      var urlContent = app.globalData.url + "api/wx/login"
      request.requestPostApi(urlContent, {}, this, null, function (res) {
        console.error(res)
      })       
    }
    },
    attached: function () {
      // 在组件实例进入页面节点树时执行
    },
    detached: function () {
      // 在组件实例被从页面节点树移除时执行
    },
  },
  //组件的函数
  methods: {
    openVideoInfo: function(){
      wx.navigateTo({
        url: 'test?id=1'
      })
    },
    urlInput: function (e) {
      this.setData({
        videoUrl: e.detail.value.trim()
      })
    },
    // 视频地址匹配是否合法
    regUrl: function (t) {
      return /(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?/.test(t)
    },
    findUrlByStr: function (t) {
      return t.match(/(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?/)
    },
    submit: function () {
      this.setData({
        isButton: false
      })
      if (this.regUrl(this.data.videoUrl)) {
        this.parseVideo();
      } else {
        this.showToast('请复制短视频平台分享链接后再来')
        this.setData({
          isButton: true
        })
      }
    },

    // 视频解析
    parseVideo: function () {
      var that = this;
      var params = {
        url: this.data.videoUrl,
        memCard: wx.getStorageSync('openId')
      };
      request.requestGetApi(app.globalData.url + 'toolapi/tDouYin/getDouyin', params, this, function (res) {
        if (res.status != 200) {
          wx.getUserProfile({
            desc: '用于展示用户信息',
            success(res) {
              var user = res.userInfo
              app.globalData.userInfo = user
              that.setData({
                userInfo: user
              }),
              that.updateUser(user.nickName)
            }
          })
          that.setData({
            isShow: true,
            isButton: true
          })
        } else {
           let obj = res.data
            that.setData({
              isShow: true,
              isButton: true,
              list: obj.images
            })
          }
      }, function (res) {
        console.error(res)
      })
    },
    updateUser(e){
      var urlContent = app.globalData.url + "api/wx/update"
      var params = {
        name: e
      };
      request.requestPostApi(urlContent, params, this, function (res) {
        if (res.status == 200) {
        }
      })
    },
    hideModal() {
      this.setData({
        isShow: false,
        isUrlDownload: false
      })
    },
    xiazai:function(e){
      wx.downloadFile({
        url: e.currentTarget.dataset.img,//图片的地址
        success:function(res){
          const tempFilePath = res.tempFilePath
          wx.saveImageToPhotosAlbum({
            filePath: tempFilePath,  //设置下载图片的地址
            success:function(){
              wx.hideLoading()
              wx.showModal({
                title: '提示',
                content: '图片已保存到相册',
                showCancel: false,
              })
            },
            fail: function (err) {
              if (err.errMsg === "saveImageToPhotosAlbum:fail:auth denied" || err.errMsg === "saveImageToPhotosAlbum:fail auth deny" || err.errMsg === "saveImageToPhotosAlbum:fail authorize no response") {
                // 这边微信做过调整，必须要在按钮中触发，因此需要在弹框回调中进行调用
                wx.showModal({
                  title: '提示',
                  content: '需要您授权保存到相册',
                  showCancel: false,
                  success: modalSuccess => {
                    wx.openSetting({
                      success(settingdata) {
                        console.log("settingdata", settingdata)
                        if (settingdata.authSetting['scope.writePhotosAlbum']) {
                          wx.showModal({
                            title: '提示',
                            content: '获取权限成功,再次点击即可保存',
                            showCancel: false,
                          })
                        } else {
                          wx.showModal({
                            title: '提示',
                            content: '获取权限失败，将无法保存到相册哦~',
                            showCancel: false,
                          })
                        }
                      },
                      fail(failData) {
                        console.log("failData", failData)
                      },
                      complete(finishData) {
                        console.log("finishData", finishData)
                      }
                    })
                  }
                })
              }
            },
            complete(res) {
              wx.hideLoading()
            }
          })
        }
      })
    },
    download: function () {
      var t = this,
      e = this.data.url;
      console.log(e)
      wx.downloadFile({
        url: e,
        success: function (o) {
          // const w= wx.getFileSystemManager().readFileSync(o,"utf-8");
          console.log("------------------"+o)
          wx.saveVideoToPhotosAlbum({
            filePath: o.tempFilePath,
            success: function (o) {
              t.showToast('视频保存成功')
              t.setData({
                isDownload: false,
                isShow: false,
              })
            },
            fail: function (o) {
              t.showToast('视频保存失败')
              t.setData({
                isDownload: false,
              })
            }
          })
        },
        fail: function (o) {
          t.setData({
            isUrlDownload: true,
            isDownload: false,
          })
        }
      })
    },
    onShareAppMessage: function () {
      return {
        path: '/pages/video/video',
      }
    },
    prevent: function () {
      // console.log(event.currentTarget.dataset.url);
      wx.setClipboardData({
        data: this.data.url,
      });
    },
    showToast: function (text) {
      wx.showToast({
        title: text,
        icon: 'none',
        duration: 2000,
        mask: true
      })
    },
    copy : function(){
      wx.getClipboardData({
        success: res => {
          var str = res.data.trim()
          if (this.regUrl(str)) {
            console.error(this.findUrlByStr(str))
            this.setData({
              videoUrl: this.findUrlByStr(str)[0],
              videoTitle: str.substring(0, 20),
              shortVideoUrl: this.findUrlByStr(str)[0].substring(0, 35) + "...",
            })
          }else{
            this.showToast("请复制短视频平台分享链接后再来")
          }
        }
      })
    }
  },
  pageLifetimes: {
    show: function () {
      // 如果剪切板内有内容则尝试自动填充
      wx.getClipboardData({
        success: res => {
          var str = res.data.trim()
          if (this.regUrl(str)) {
            wx.showModal({
              title: '检测到剪切板有视频地址，是否自动填入？',
              success: res => {
                if (res.confirm) {
                  this.setData({
                    videoUrl: this.findUrlByStr(str)[0],
                    videoTitle: str.substring(0, 20),
                    shortVideoUrl: this.findUrlByStr(str)[0].substring(0, 35) + "...",
                  })
                }
              }
            })
          }
        }
      })
    },
    hide: function () {
      // 页面被隐藏
    },
    resize: function (size) {
      // 页面尺寸变化
    }
  }
})